# Api中间件层, 所以关于Api的请求都必须经过此中间件
from django.utils.deprecation import MiddlewareMixin
from BlackWidow.models import User
from BlackWidow.tools import tools
from django.http import JsonResponse
class Api(MiddlewareMixin):
    def process_request(self, request):
        if tools.is_not_valid_path_user_id(request) == False:
            return None
        # 获取用户ID
        user_id = request.META.get("HTTP_X_USER_ID")
        if not user_id:
            return JsonResponse({"code": 401, "msg": "请先登录", "data":tools.get_login_url(request)})
        user = User.objects.filter(user_id=user_id).first()
        if not user:
            return JsonResponse({"code": 401, "msg": "没有找到用户", "data":tools.get_login_url(request)})
        # 把用户模型附加到request中
        request.user = user
        return None

    def process_response(self, request, response):
        return response



